<template>
  <div>
    <h1>Proxy与Reflect</h1>
    <h1>{{ store.state.number }}</h1>
    <h1>{{ store.state.a.aa }}</h1>
    <h1>{{ store.getters.mynumber }}</h1>
    <button @click="updateNumber">增加</button>
  </div>
</template>

<script lang="ts">
import {useStore} from 'vuex'

export default {
  name: "Reactive",
  setup() {
    const store = useStore();
    console.log(store.state.number)
    const updateNumber = () => {
      // store.commit('SET_NUMBER', store.state.number * 2)
      store.dispatch('setNumber', store.state.number * 8)
      store.commit('SET_AA', store.state.a.aa * 9)
    }
    const user = {
      name: "John",
      age: 12
    };
    /*
    proxyUser是代理对象, user是被代理对象
    后面所有的操作都是通过代理对象来操作被代理对象内部属性
    */
    const proxyUser = new Proxy(user, {

      get(target, prop) {
        console.log('劫持get()', prop)
        return Reflect.get(target, prop)
      },

      set(target, prop, val) {
        console.log('劫持set()', prop, val)
        return Reflect.set(target, prop, val); // (2)
      },

      // setPrototypeOf(target, prop, val) {
      //   console.log('劫持setPrototypeOf()', prop, val)
      //   return Reflect.setPrototypeOf(target, prop, val)
      // },

      deleteProperty(target, prop) {
        console.log('劫持delete属性', prop)
        return Reflect.deleteProperty(target, prop)
      }
    });
    // 读取属性值
    //console.log(proxyUser === user)
    // console.log(proxyUser.name, proxyUser.age)
    // 设置属性值
    proxyUser.name = 'bob'
    proxyUser.age = 13
    //console.log(user)
    // 添加属性
    //TODO 添加新属性
    // proxyUser.sex = '男'
    // console.log(user)
    // proxyUser.sex = 'M'
    // TODO 删除属性
    // delete proxyUser.name
    // console.log(user)
    //delete proxyUser.name
    return {
      updateNumber,
      store
    }
  }
}
</script>

<style scoped>

</style>
